import 'package:flutter/material.dart';

class GalleryFrameAnimationPainter extends CustomPainter {
  List<List<Color>> frameData;
  ///间距
  final double? pointSpace;

  GalleryFrameAnimationPainter(this.frameData, {this.pointSpace});

  @override
  void paint(Canvas canvas, Size size) {
    double minLength;
    double offsetX = 0;
    double offsetY = 0;

    int displayWidth = size.width.toInt();
    int displayHeight = size.height.toInt();
    double displayRatio = displayWidth / displayHeight;

    int imageWidth = frameData.length;
    if(imageWidth == 0){
      return;
    }
    int imageHeight = frameData.first.length;
    double imageRatio = imageWidth / imageHeight;


    double padding;
    int count;
    if (displayRatio < imageRatio) {
      minLength = size.width;
      offsetY = (displayHeight - displayWidth/imageRatio) * 0.5;
      count = frameData.length;
    } else if(displayRatio > imageRatio){
      minLength = size.height;
      offsetX = (displayWidth - displayHeight*imageRatio) * 0.5;
      count = frameData.first.length;
    }else{
      minLength = size.width;
      count = frameData.length;
    }

    if(pointSpace != null){
      padding = pointSpace!;
    }else{
      padding = minLength/count*0.2;
    }


    double pointSize = (minLength - ((count - 1) * padding)) / count;

    for (int j = 0; j < frameData.length; j++) {
      var dx = (pointSize + padding) * j + offsetX;
      for (int z = 0; z < frameData[j].length; z++) {
        var dy = (pointSize + padding) * z + offsetY;
        var pixel = frameData[j][z];
        canvas.drawRect(
            Rect.fromPoints(
                Offset(dx, dy), Offset(dx + pointSize, dy + pointSize)),
            Paint()
              ..style = PaintingStyle.fill
              ..color = pixel);
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
